package controller

import (
	"fmt"
	"github.com/go-pay/gopay"
	"ksd-social-api/commons/base/controller"
	utils2 "ksd-social-api/utils"
	"strconv"
)

type AlipayNativeSpecialController struct {
	controller.BaseController
	AlipayPayBaseController
}

/**
 * 支付宝支付-专栏
 * @author feige
 * @date 2023-12-04
 * @version 1.0
 * @desc
 */
func (web *AlipayNativeSpecialController) NativePay() {
	// ?
	client, ctx := web.GetAlipayPayClient()
	if nil == client {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	uvo := userService.GetUserById(web.GetUserId(), web.GetSystemId())
	if nil == uvo {
		web.FailCodeMsg(901, "没找到支付用户")
		return
	}

	// 查询用户身份对应的折扣
	_d := 1.0
	userVip := userVipService.GetUserVipDetailByViptype(uvo.VipFlag)
	if nil != userVip {
		_d = userVip.Discount
	}

	// 专栏业务
	specialId, _ := web.ParseParamUint64("opid")
	specialDetailPayVo, err := specialService.GetSpecialByIDToPay(specialId, web.GetSystemId())
	if err != nil {
		web.FailCodeMsg(901, "支付的专栏不存在！")
		return
	}
	OutTradeNo := web.GetSnowWorkerIdString(11)
	// 查询用户已经支付的小册
	sumPrice := userNoteService.SumUserByNote(specialId, web.GetUserId(), web.GetSystemId())
	totalPrice, _ := strconv.ParseFloat(specialDetailPayVo.Price, 10)
	if sumPrice >= totalPrice {
		userSpecialService.SaveUserSpecial(
			OutTradeNo, OutTradeNo, "课程升级", 2, "支付宝", specialDetailPayVo.Price,
			web.GetUserId(), specialId, web.GetSystemId(), web.GetSystemName())
		web.FailCodeMsg(909, "尊敬的学员【"+web.GetUsername()+"】您好，你单次购买课程的金额已经大于等于课程金额，自动升级课程权限！")
		return
	} else {
		totalPrice = totalPrice - sumPrice
	}

	// 参数map ?
	mattch := map[string]any{}
	mattch["userId"] = web.GetUserId()
	mattch["opid"] = specialId
	mattch["systemId"] = web.GetSystemId()
	mattch["type"] = "special"
	mattch["price"] = totalPrice * _d

	fmt.Println("阿里支付：OutTradeNo", OutTradeNo)
	//请求参数
	bm := make(gopay.BodyMap)
	bm.Set("subject", specialDetailPayVo.Title)
	bm.Set("out_trade_no", fmt.Sprintf("%s_%s_%d_%d", OutTradeNo, "special", web.GetUserId(), specialId))
	bm.Set("total_amount", totalPrice)
	// 发起交易
	m := map[string]any{}
	// 阿里支付生成支付链接
	aliRsp, err := client.TradePrecreate(ctx, bm)
	if err != nil {
		// 处理错误
		m["url"] = ""
		m["status"] = "fail"
		m["tradeNo"] = ""
	} else {
		// 处理返回结果
		m["url"] = aliRsp.Response.QrCode
		m["tradeNo"] = aliRsp.Response.OutTradeNo
		m["status"] = "success"
	}

	web.Ok(m)
}

/**
 * 专栏回调
 * @author feige
 * @date 2023-12-04
 * @version 1.0
 * @desc
 */
func (web *AlipayNativeSpecialController) QueryOrderByOutTradeNo() {
	// 获取支付的交易编号
	OutTradeNo := web.GetString("tradeno")
	client, ctx := web.GetAlipayPayClient()
	if nil == client {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	//请求参数
	bm := make(gopay.BodyMap)
	bm.Set("out_trade_no", OutTradeNo)
	aliRsp, err := client.TradeQuery(ctx, bm)
	if err != nil {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	response := aliRsp.Response
	// TRADE_FINISHED
	tmp := make(map[string]interface{})
	if response.TradeStatus == "TRADE_SUCCESS" {
		specialId, _ := web.GetUint64("opid")
		isBuyFlag := userSpecialService.CountUserBuySpecial(web.GetUserId(), specialId, web.GetSystemId())
		if !isBuyFlag {
			web.FailCodeMsg(902, "用户已经购买此专栏!")
			return
		}
		// 订单保存落库
		userSpecialService.SaveUserSpecial(
			response.OutTradeNo, response.TradeNo, utils2.StructToJson(response), 2, "支付宝", response.TotalAmount,
			web.GetUserId(), specialId, web.GetSystemId(), web.GetSystemName())
		//支付宝支付回调返回特殊处理，Flag = 40
		tmp["code"] = "SUCCESS"
		tmp["message"] = "成功"
		web.Ok(tmp)
	} else {
		web.FailCodeMsg(901, "fail")
	}
}
